package com.gec.service;

import com.gec.entity.SysRole;
import com.gec.entity.SysUser;
import com.gec.mapper.SysRoleMapper;
import com.gec.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service(value = "JdbcUserDetailsService")
@Slf4j
public class JdbcUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据username从数据库获取SysUser
        if (username != null) {
            SysUser user = sysUserMapper.selectSysUser(username);

            if (user != null) {
                log.info("获取到用户信息:{}", user);

                //根据userid获取roles
                List<SysRole> roles = sysRoleMapper.selectRolesByUser(user.getId());

                if (roles != null && roles.size() > 0) {
                    //构建用户角色
                    List<GrantedAuthority> authorities = new ArrayList<>();

                    for (SysRole role : roles) {
                        String name = role.getName();
                        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + name);
                        authorities.add(authority);
                    }
                    //将构造的角色列表设置进user中
                    user.setAuthorities(authorities);
                }
            }
            return user;
        }
        return null;
    }
}
